<?php

/**
 * 框架核心函数
 */

use core\lib\tool\Token;


if (!function_exists('get_now_url')) {
    /**
     * 获取当前的地址
     *
     * @param boolean $onlypath TRUE 仅仅获取PATH 
     * @return string
     */
    function get_now_url(bool $onlypath = true): string
    {
        $uri = request()->uri();
        return $onlypath ? explode('?', $uri)[0] : $uri;
    }
}


if (!function_exists('is_post')) {
    /**
     * 是否post提交
     *
     * @return boolean
     */
    function is_post()
    {
        return strtolower(request()->method()) == 'post';
    }
}

if (!function_exists('is_get')) {
    /**
     * 是否get提交
     *
     * @return boolean
     */
    function is_get()
    {
        return strtolower(request()->method()) == 'get';
    }
}


if (!function_exists('get_controller')) {

    /**
     * 获取控制器名称
     *
     * @return string
     */
    function get_controller(): string
    {

        if (strpos(request()->uri(), '/widget/') === 0) {
            $uris = explode('/', request()->uri());
            return isset($uris[3]) ? $uris[3]  : '';
        }

        if (strpos(request()->uri(), '/element/') === 0) {
            $uris = explode('/', request()->uri());
            return isset($uris[3]) ? $uris[3]  : '';
        }

        if (strpos(request()->uri(), '/extend/') === 0) {
            $uris = explode('/', request()->uri());
            return isset($uris[3]) ? $uris[3]  : '';
        }


        $controller = request()->controller;
        $controller_arr = explode('\\controller\\', $controller);
        if (isset($controller_arr[1])) {
            return str_replace('\\', '/', $controller_arr[1]);
        }
        return '';
    }
}

if (!function_exists('get_action')) {
    /**
     * 获取控制器名
     *
     * @return string
     */
    function get_action(): string
    {
        if (strpos(request()->uri(), '/widget/') === 0) {
            $uris = explode('/', request()->uri());
            return isset($uris[4]) ? explode('?', $uris[4])[0]  : '';
        }
        if (strpos(request()->uri(), '/element/') === 0) {
            $uris = explode('/', request()->uri());
            return isset($uris[4]) ? explode('?', $uris[4])[0]  : '';
        }

        if (strpos(request()->uri(), '/extend/') === 0) {
            $uris = explode('/', request()->uri());
            return isset($uris[4]) ? explode('?', $uris[4])[0]  : '';
        }
        return request()->action;
    }
}


if (!function_exists('get_plugin')) {
    /**
     * 获取应用插件名
     *
     * @return string
     */
    function get_plugin():string
    {
        if (!is_plugin()) {
            return '';
        }
        return explode('\\', request()->controller)[1];
    }
}


if (!function_exists('get_widget')) {
    /**
     * 获取挂件
     *
     * @return string
     */
    function get_widget():string
    {
        $uri = request()->uri();
        if (strpos($uri, '/widget/') !== 0) {
            return '';
        }
        $uriarr = explode('/', $uri);
        return isset($uriarr[2]) ? $uriarr[2] : '';
    }
}


if (!function_exists('get_element')) {

    /**
     * 获取当前路径元素名（文件夹名）
     *
     * @return string
     */
    function get_element(): string
    {
        $uri = request()->uri();
        if (strpos($uri, '/element/') !== 0) {
            return '';
        }
        $uriarr = explode('/', $uri);
        return isset($uriarr[2]) ? $uriarr[2] : '';
    }
}


if (!function_exists('get_extend')) {

    /**
     * 获取当前路径元素名（文件夹名）
     *
     * @return string
     */
    function get_extend(): string
    {
        $uri = request()->uri();
        if (strpos($uri, '/extend/') !== 0) {
            return '';
        }
        $uriarr = explode('/', $uri);
        return isset($uriarr[2]) ? $uriarr[2] : '';
    }
}


if (!function_exists('is_plugin')) {
    /**
     * 当前访问的地址是否是 应用插件
     *
     * @return boolean
     */
    function  is_plugin(): bool
    {
        $controller = request()->controller;
        return substr($controller, 0, 7) == 'plugin\\';
    }
}

if (!function_exists('is_element')) {
    /**
     * 当前地址是否是组件元素
     *
     * @return boolean
     */
    function is_element(): bool
    {
        return  strpos(request()->uri(), '/element/') === 0;
    }
}

if (!function_exists('is_widget')) {
    /**
     * 当前地址是否是组件元素
     *
     * @return boolean
     */
    function is_widget(): bool
    {
        return  strpos(request()->uri(), '/widget/') === 0;
    }
}


if (!function_exists('get_plugin_viewpath')) {
    /**
     * 获取应用插件视图模板地址
     *
     * @return string
     */
    function get_plugin_viewpath(string $plugin = ''): string
    {

        if (!$plugin && !is_plugin()) {
            return '';
        }
        return '/plugin/' . ($plugin ? $plugin : get_plugin()) . '/app/view/';
    }
}

if (!function_exists('get_extend_path')) {
    /**
     * 扩展组件路径
     *
     * @return string
     */
    function get_extend_path(): string
    {
        return base_path() . '/component/extend/';
    }
}


if (!function_exists('get_element_path')) {
    /**
     * 扩展元素控件路径
     *
     * @return string
     */
    function get_element_path(bool $basepath = true): string
    {
        return ($basepath ? base_path() : '') . '/component/element/';
    }
}

if (!function_exists('getDatabasePrefix')) {
    /**
     * 数据库前缀
     *
     * @return string
     */
    function getDatabasePrefix(): string
    {
        $conndef = config('database.default');
        return config('database.connections.' . $conndef . '.prefix');
    }
}


if (!function_exists('anypath_view')) {
    function anypath_view(string $path, array $vars = [])
    {
        request()->_view_vars = array_merge((array) request()->_view_vars, $vars);
        extract((array)request()->_view_vars);
        ob_start();
        try {
            include $path;
            foreach ((array)request()->_view_vars as $var) {

                unset($var);
            }
        } catch (Throwable $e) {
            ob_end_clean();
            throw $e;
        }
        return ob_get_clean();
    }
}

if (!function_exists('element')) {
    function element(string $element, ...$param)
    {

        $reflectionClass = new ReflectionClass(
            'component\\element\\'
                . $element
                . '\\controller\\Index'
        );

        $method = $reflectionClass->getMethod('index');
        if ($method->isPublic()) {
            $instance = $reflectionClass->newInstance();
            return $method->invoke($instance, ...$param);
        }
    }
}


if (!function_exists('widget')) {
    function widget(string $widget, ...$param)
    {

        $reflectionClass = new ReflectionClass(
            'component\\widget\\'
                . str_replace('/', '\\', $widget)
                . '\\controller\\Index'
        );

        $method = $reflectionClass->getMethod('index');
        if ($method->isPublic()) {
            $instance = $reflectionClass->newInstance();
            return $method->invoke($instance, ...$param);
        }
    }
}


if (!function_exists('component_static_path')) {
    /**
     * 返回组件的静态文件地址
     *
     * @param string $component 组件 名
     * @param string $type 组件类型
     * @return string
     */
    function component_static_path(string $component, string $type = 'element'): string
    {
        return '/component/' . $type . '/' . $component . '/static/';
    }
}

if (!function_exists('is_management_backend')) {
    /**
     * 当前访问的地址是否是管理后台的地址  
     * @param string $url URI 的path部分
     * @return boolean
     */
    function is_management_backend(string $url = ''): bool
    {
        $url    =  $url == '' ? get_now_url() : $url;
        $urlarr = explode('/', $url);
        if (is_plugin()) {
            return isset($urlarr[3]) && strtolower($urlarr[3]) == 'admin';
        }
        return isset($urlarr[1]) && strtolower($urlarr[1]) == 'admin';
    }
}

if (!function_exists('element_safe_token')) {
    function element_safe_token(string $element = '')
    {
        return Token::issueToken([
            'element'    => $element,
            'url'        => get_now_url(),
            'controller' => get_controller(),
            'plugin'     => get_plugin(),
            'time'       => time(),
        ], 86400);
    }
}

if (!function_exists('enumLabel')) {
    /**
     * 返回枚举的名称和值
     *
     * @param string $enumname 
     * @return array
     */
    function enumLabel(string $enumname): array
    {
        $enumclass = '\\app\\enum\\' . $enumname;
        $cases = $enumclass::cases();
        $label = [];
        foreach ($cases as $case) {
            $label[$case->value] = [
                'value' => $case->value,
                'title' => $case->title(),
                'color' => $case->color()
            ];
        }
        return $label;
    }
}


if (!function_exists('enumLabel_titlekey')) {
    /**
     *返回枚举的名称和值 TITLE作为键值
     *
     * @param string $enumname
     * @return array
     */
    function enumLabel_titlekey(string $enumname): array
    {
        $enumclass = '\\app\\enum\\' . $enumname;
        $cases = $enumclass::cases();
        $label = [];
        foreach ($cases as $case) {
            $label[$case->title()] = [
                'value' => $case->value,
                'title' => $case->title(),
                'color' => $case->color()
            ];
        }
        return $label;
    }
}

if (!function_exists('get_component_static_path')) {
    /**
     * 返回组件的静态文件地址
     *
     * @param string $type
     * @return string
     */
    function get_component_static_path(string $type = 'element'): string
    {
        return '/component/' . $type . '/';
    }
}
